import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by KaiseRR on 23.02.15.
 */
public class MessageSender extends Thread {

    private boolean isStopped;
    private OutputStream out;
    private MessageCenter messageCenter;

    public MessageSender(OutputStream out, MessageCenter messageCenter) {
        this.out = out;
        this.messageCenter = messageCenter;
        this.setDaemon(true);
    }

    public void run() {
        while (!isStopped) {
            try {
                sendMessage(messageCenter.getMessageToSend());
            } catch (IOException e) {
                e.printStackTrace();
                stopThread();
            }
        }
    }

    public void stopThread() {
        isStopped = true;
        messageCenter.setDestroyed();
    }

    public void sendMessage(String message) throws IOException {
        if (message != null && message.length() > 0) {
            out.write(message.getBytes());
            out.flush();
        }
    }

    public boolean isStopped() {
        return isStopped;
    }
}
